import { Injectable, ServiceUnavailableException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { ListGoodsDto } from 'src/module/grocery/dto/goods/list-goods.dto';
import { Goods } from 'src/module/grocery/entities/goods.entity';
import { GoodsService } from 'src/module/grocery/service/goods.service';

@Injectable()
export class ProductService {
  constructor(
    private readonly productService: GoodsService,
    @InjectRepository(Goods, 'shop')
    private readonly productRepository: Repository<Goods>,
  ) {}

  async findOne(id: number) {
    try {
      const res = await this.productRepository.findOneBy({
        id,
        isDelete: 1,
      });
      return res;
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }

  async findAll(listGoodsDto: ListGoodsDto) {
    try {
      const {
        id = null,
        title = '',
        desc = '',
        categoryId = null,
      } = listGoodsDto.queryDto;
      const queryBuilder = this.productRepository.createQueryBuilder('goods');

      if (id) {
        queryBuilder.where('goods.id = :id', { id });
      }

      if (categoryId) {
        queryBuilder.andWhere('goods.category_id = :categoryId', { categoryId });
      }

      queryBuilder
        .andWhere('goods.is_delete = :isDelete', { isDelete: 1 })
        .andWhere('goods.is_promotion = :isPromotion AND goods.is_hot = :isHot', {
          isPromotion: 0,
          isHot: 0,
        })
        .andWhere('goods.title LIKE :title AND goods.desc LIKE :desc', {
          title: `%${title}%`,
          desc: `%${desc}%`,
        });

      const [list, total] = await queryBuilder
        .orderBy('goods.modify_time', 'DESC')
        .skip((listGoodsDto.pageDto.pageNo - 1) * listGoodsDto.pageDto.pageSize)
        .take(listGoodsDto.pageDto.pageSize)
        .getManyAndCount();

      return {
        list,
        total,
        ...listGoodsDto.pageDto,
      };
    } catch (e) {
      throw new ServiceUnavailableException();
    }
  }
}
